<?php

namespace App\Models;

use Dcat\Admin\Admin;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class AdminUser extends Administrator
{
    use HasDateTimeFormatter;

    protected $table = 'admin_users';

    /***
     * 关联部门
     * @return BelongsToMany
     */
    public function departments()
    {
        return $this->hasOne(Department::class, 'id', 'department_id',);
    }

    /**
     * 获取指定角色的用户
     * @param string|array $str
     *
     */
    public function alluser($str)
    {
        if (is_array($str)) {
            $pivotTable = config('admin.database.role_users_table');
            $relatedModel = config('admin.database.roles_model');
            $relatedModel = new $relatedModel();
            $pivotTable = DB::table($pivotTable);
            $slug_id = $relatedModel->whereIn('slug', $str)->select('id')->get();
            $slug_ids = array_column($slug_id->toArray(), 'id');
            $userids = $pivotTable->whereIn('role_id', $slug_ids)->distinct()->pluck('user_id')->toArray();
            return Administrator::whereIn('id', $userids)->get();
        } elseif (is_string($str)) {
            $pivotTable = config('admin.database.role_users_table');
            $relatedModel = config('admin.database.roles_model');
            $relatedModel = new $relatedModel();
            $pivotTable = DB::table($pivotTable);
            $slug_id = $relatedModel->where('slug', $str)->value('id');
            $userids = $pivotTable->where('role_id', $slug_id)->pluck('user_id')->toArray();
            return Administrator::whereIn('id', $userids)->get();
        }
    }


}
